from core.faker import FAKER_FUNC_MAP
from core.common import single_replace_data, formatter_log, set_func_extract
from apps.tests.models import CaseRunLog
from apps.scripts.models import PythonScript
from core.step_model import StepModel
from core.check import loop_assert_by_check_list


def run_step_inner_func(manager_obj, steps, step_key, env_id, one_step_data: StepModel, params_class, case_logs_obj):
    params_list = []
    for params_obj in one_step_data.params:
        if params_obj.type != 'Dynamic':
            params_list.append(params_obj.value)
        else:
            params_obj.value = single_replace_data(params_class, case_logs_obj, params_obj.value)
            params_list.append(params_obj.value)

    return_value = FAKER_FUNC_MAP[step_key](*tuple(params_list))
    case_logs_obj.logs.append(formatter_log('success', '【{} 函数返回值为: {}】'.format(step_key, return_value)))
    set_func_extract(return_value, one_step_data.extract, case_logs_obj, params_class)
    # 执行步骤的断言参数,如果步骤中有断言数据则忽略接口的断言数据
    loop_assert_by_check_list(one_step_data.check, params_class, case_logs_obj)


def run_step_script(manager_obj, steps, step_key, env_id, one_step_data: StepModel, params_class, case_logs_obj):
    params_list = []
    for params_obj in one_step_data.params:
        if params_obj.type != 'Dynamic':
            params_list.append(params_obj.value)
        else:
            params_obj.value = single_replace_data(params_class, case_logs_obj, params_obj.value)
            params_list.append(params_obj.value)

    script_obj = PythonScript.objects.all().get(id=step_key)
    exec(script_obj.script)
    return_value = locals()[script_obj.name](*params_list, params_class, case_logs_obj)
    case_logs_obj.logs.append(formatter_log('success', '【{} 函数返回值为: {}】'.format(script_obj.name, return_value)))
    set_func_extract(return_value, one_step_data.extract, case_logs_obj, params_class)
    # 执行步骤的断言参数,如果步骤中有断言数据则忽略接口的断言数据
    loop_assert_by_check_list(one_step_data.check, params_class, case_logs_obj)
